/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Damaged;
import com.jeeplus.modules.ap.entity.Fine;
import com.jeeplus.modules.ap.service.DamagedService;
import com.jeeplus.modules.ap.service.FineService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.Dispatching;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.entity.NbFine;
import com.jeeplus.modules.ap.service.NbFineService;

/**
 * 内部考核Controller
 * @author 李超辉
 * @version 2019-08-08
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/nbFine")
public class NbFineController extends BaseController {

	@Autowired
	private NbFineService nbFineService;
	@Autowired
	private FineService fineService;
	@Autowired
	private DamagedService damagedService;
	
	@ModelAttribute
	public NbFine get(@RequestParam(required=false) String id) {
		NbFine entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = nbFineService.get(id);
		}
		if (entity == null){
			entity = new NbFine();
		}
		return entity;
	}
	
	/**
	 * 内部考核列表页面
	 */
	@RequiresPermissions("ap:nbFine:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/nbFineList";
	}
	
		/**
	 * 内部考核列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:nbFine:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(NbFine nbFine, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<NbFine> page = nbFineService.findPage(new Page<NbFine>(request, response), nbFine); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑内部考核表单页面
	 */
	@RequiresPermissions(value={"ap:nbFine:view","ap:nbFine:add","ap:nbFine:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(NbFine nbFine, Model model) {
		if(nbFine.getIsNewRecord()){
			String pro= UserUtils.getUseroffice();
			nbFine.setBsc(UserUtils.getbsc());
			if(!pro.equals("总部")){
				nbFine.setPro(pro);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			NbFine p=new NbFine();
			p.setCode(code);
			List<NbFine> l=nbFineService.findList(p);
			if(l==null||l.size()<1){
				nbFine.setCode(code+"001"+"NBKH");
			}else{
				if(l.size()/10==0){
					nbFine.setCode(code+"00"+(l.size()+1)+"NBKH");
				}else
				if(l.size()/100==0){
					nbFine.setCode(code+"0"+(l.size()+1)+"NBKH");
				}else{nbFine.setCode(code+(l.size()+1)+"NBKH");}

			}
		}
		model.addAttribute("nbFine", nbFine);
		return "modules/ap/nbFineForm";
	}

	/**
	 * 保存内部考核
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:nbFine:add","ap:nbFine:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(NbFine nbFine, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, nbFine)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		String wb=nbFine.getWbfk();
		String hs=nbFine.getHs();
		Fine f=fineService.findUniqueByProperty("code",wb);
		Damaged dm=damagedService.findUniqueByProperty("code",hs);
		if(f==null||f.getId().equals("")){
			j.setSuccess(false);
			j.setMsg("请检查外部考核号");
			return j;
		}
		if(dm==null||dm.getId().equals("")){
			j.setSuccess(false);
			j.setMsg("请检查货损单号");
			return j;
		}
		nbFineService.save(nbFine);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存内部考核成功");
		return j;
	}
	
	/**
	 * 删除内部考核
	 */
	@ResponseBody
	@RequiresPermissions("ap:nbFine:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(NbFine nbFine, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		nbFineService.delete(nbFine);
		j.setMsg("删除内部考核成功");
		return j;
	}
	
	/**
	 * 批量删除内部考核
	 */
	@ResponseBody
	@RequiresPermissions("ap:nbFine:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			nbFineService.delete(nbFineService.get(id));
		}
		j.setMsg("删除内部考核成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:nbFine:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(NbFine nbFine, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "内部考核"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<NbFine> page = nbFineService.findPage(new Page<NbFine>(request, response, -1), nbFine);
    		new ExportExcel("内部考核", NbFine.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出内部考核记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:nbFine:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<NbFine> list = ei.getDataList(NbFine.class);
			for (NbFine nbFine : list){
				try{
					nbFineService.save(nbFine);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条内部考核记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条内部考核记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入内部考核失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/nbFine/?repage";
    }
	
	/**
	 * 下载导入内部考核数据模板
	 */
	@RequiresPermissions("ap:nbFine:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "内部考核数据导入模板.xlsx";
    		List<NbFine> list = Lists.newArrayList(); 
    		new ExportExcel("内部考核数据", NbFine.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/nbFine/?repage";
    }

}